package kaist.sep521.lego.circlebicycle;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.app.Activity;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MakeGroupActivity extends Activity {
	EditText name;
	EditText description;

	// Alphabet + Number
	protected InputFilter filterAlphaNum = new InputFilter() {
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			Pattern ps = Pattern.compile("^[a-zA-Z0-9\\.\\p{Space}]+$");
			if (!ps.matcher(source).matches()) {
				return "";
			} 
			return null;
		} 
	}; 


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_make_group);

		name = (EditText)findViewById(R.id.newGroup_name);
		description = (EditText)findViewById(R.id.newGroup_desc);
		name.setFilters(new InputFilter[]{filterAlphaNum});
		description.setFilters(new InputFilter[]{filterAlphaNum});


		final Button ok = (Button)findViewById(R.id.newGroup_ok);
		final Button cancel = (Button)findViewById(R.id.newGroup_back);


		ok.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// request to make new group
				String circlename = name.getText().toString();
				String circleinfo = description.getText().toString();

				String result = makeCircle(circlename, circleinfo);

				if (result == "true"){
					circleJoin(circlename);
					hideKeyboard();
					onBackPressed();
				}else{
					Toast.makeText(MakeGroupActivity.this, "Fail to make new group", Toast.LENGTH_SHORT).show();
				}
			}
		});

		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				hideKeyboard();
				onBackPressed();
			}
		});
	}

	private void hideKeyboard() {
		InputMethodManager inputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(description.getWindowToken(),0);
	}

	public String makeCircle(String circleName, String circleInfo) {

		String makeCircleUrl="http://14.63.196.253/~lego/makeCircle.php";
		Log.e("Responce-->", "makeCircle");
		Log.e("Responce-->", "name"+circleName);
		Log.e("Responce-->", "info"+circleInfo);
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		Log.e("Responce-->", "after httpclient");
		/* login.php returns true if username and password is equal to saranga */
		HttpPost httppost = new HttpPost(makeCircleUrl);

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("name", circleName));
			nameValuePairs.add(new BasicNameValuePair("info", circleInfo));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			Log.e("Responce-->", "after using the list name pair");

			// Execute HTTP Post Request
			Log.w("SENCIDE", "Execute HTTP Post Request");
			HttpResponse response = httpclient.execute(httppost);
			Log.e("Responce-->", "after execute the http response");

			String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

			Log.e("Responce-->", "" + str);

			if (str.toString().equalsIgnoreCase("true")) {
				Log.w("SENCIDE", "TRUE");
				return ("true");
			} else {
				Log.w("SENCIDE", "FALSE");
				return (str);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ("Network Connection Error. Please, try again.");

	}

	private void circleJoin(String groupname) {
		String user = MainActivity.myInfo.getID();
		String joinedGroup = MainActivity.myInfo.getGroup();

		String cexitUrl = "http://14.63.196.253/~lego/groupjoin.php?user=" + user + "&group=" + groupname;

		if (groupname.equals(joinedGroup)){
			Toast.makeText(MakeGroupActivity.this, "You are already joined this "+ groupname + " Circle.", Toast.LENGTH_SHORT).show();
		}else{
			//Clear the Voice Tag on the server.
			try {
				URL url = new URL(cexitUrl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					MainActivity.myInfo.setGroup(groupname);
					Log.w("Circle JOIN", "HTTP_SEND_OK");

				} else {
					Toast.makeText(MakeGroupActivity.this, "Server connection error!!", Toast.LENGTH_SHORT).show();
				}
				conn.disconnect();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
